package com.example.appcontact;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.base.BaseActivity;
import com.example.component.LoadingDialogComponent;
import com.example.connect.AsyncTask_Api;
import com.example.connect.AsyncTask_ApiListener;
import com.example.connect.CallApi;
import com.example.connect.ScreenStopper;
import com.example.model.OutResult;
import com.example.util.ConnectionException;
import com.example.util.EmptyDataException;
import com.example.util.TokenUnableException;
import com.example.util.Util;

public class A001NewUser extends BaseActivity implements OnClickListener, OnItemSelectedListener,AsyncTask_ApiListener{
	
	private final String TAG = A001NewUser.class.getName();
	
	private Button btn_birthday;
	private TextView tv_login, tv_register, tv_title;
	private EditText et_firstname, et_lastname, et_password, et_email, et_confirmemail;
	private Spinner sn_gender;
    private long birthday  = new Date().getTime();
    private Context mContext;
    
    private HashMap<String,String> hashMap;
    
    private String mGender;
    private String key_md5;

    static final int DATE_DIALOG_ID = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		initView();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	private void initView()
	{
		
		setContentView(R.layout.a001);
		
		this.mContext = this;
		
		
		this.tv_login = (TextView)this.findViewById(R.id.header_tv_back);
		this.tv_title = (TextView)this.findViewById(R.id.header_tv_title);
		this.tv_register = (TextView)this.findViewById(R.id.header_tv_next);
		
		this.tv_login.setVisibility(View.VISIBLE);
		this.tv_register.setVisibility(View.VISIBLE);
		this.tv_title.setText(this.getResources().getString(R.string.newuser));
		
		this.btn_birthday = (Button)this.findViewById(R.id.a001_btn_birthday);
		this.et_firstname = (EditText)this.findViewById(R.id.a001_et_firstname);
		this.et_lastname = (EditText)this.findViewById(R.id.a001_et_lastname);
		this.et_password = (EditText)this.findViewById(R.id.a001_et_password);
		this.et_email = (EditText)this.findViewById(R.id.a001_et_email);
		this.et_confirmemail = (EditText)this.findViewById(R.id.a001_et_confirmemail);
		this.sn_gender = (Spinner)this.findViewById(R.id.a001_sn_gender);
		
		this.tv_register.setText(this.getResources().getString(R.string.registry));
		this.tv_login.setText(this.getResources().getString(R.string.back));
		
		this.tv_login.setOnClickListener(this);
		this.tv_register.setOnClickListener(this);
		this.btn_birthday.setOnClickListener(this);
		this.sn_gender.setOnItemSelectedListener(this);
		
		initData();
	}
	
	private void initData()
	{
		this.key_md5 = this.getResources().getString(R.string.md5_key);
		
		
        // get current date
         birthday  = new Date().getTime();

        // display the current date (this method is below)
        updateDisplay();
        
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.header_tv_back:
			Intent i = new Intent(this, A002Login.class);
			setResult(1, i);
			finish();
			break;
		case R.id.header_tv_next:
			callRegistry();
			break;
		case R.id.a001_btn_birthday:
			showDialog(DATE_DIALOG_ID);
			break;
		default:
			break;
		}
	}
	
	// updates the date in the TextView
    private void updateDisplay() {
    	Date t  = new Date(birthday);
		String newstring = new SimpleDateFormat("dd/MM/yyyy").format(t);
		btn_birthday.setText(newstring);  
    }

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                	Calendar  calendar  = Calendar.getInstance();
        			calendar.set(year, monthOfYear, dayOfMonth);
        			birthday  = calendar.getTimeInMillis();
        			Date t  = new Date(birthday);
        			String newstring = new SimpleDateFormat("dd/MM/yyyy").format(t);
        			btn_birthday.setText(newstring);
                }
            };

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			Date t  = new Date(birthday);
			Calendar  calendar  = Calendar.getInstance();
			calendar.setTime(t);
			return new DatePickerDialog(this, mDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		this.mGender = arg0.getItemAtPosition(arg2).toString();
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Object callApi(int serachType, Object apidata) {
	    OutResult out = new OutResult();
	    
			    try{
			        out = CallApi.getRegister(this, this.hashMap);
			}catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			}catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			}catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			}catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		// TODO Auto-generated method stub
		try
		{
			OutResult out = (OutResult) apiresult;
				if(out.getStatus())
				{
					Util.showDialog(A001NewUser.this, R.string.registry, out.getMessage(), R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							callA002();
						}
					});
				}
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	
	private void callA002()
	{
		Intent i = new Intent(this, A002Login.class);
		i.putExtra("username", et_email.getText().toString().trim());
		i.putExtra("password", et_password.getText().toString().trim());
		setResult(0, i);
		finish();
	}
	
	private boolean isEmptyAll(String FirstName, String LastName, String Password, String Email, String ComfirmEmail)
	{
		try
		{
			if(TextUtils.isEmpty(FirstName) || TextUtils.isEmpty(LastName) || TextUtils.isEmpty(Password) || 
					TextUtils.isEmpty(Email) || TextUtils.isEmpty(ComfirmEmail))
				return true;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			
		}
		return false;
	}
	
	private boolean isEmailValid(String Email, String ComfirmEmail)
	{
		try 
		{
			if(!Util.isEmailValid(Email) || !Util.isEmailValid(ComfirmEmail))
				return false;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			
		}
		return true;
	}
	
	private boolean isEqualMail(String Email, String ComfirmEmail)
	{
		try
		{
			if(Util.checkEqualString(Email, ComfirmEmail))
				return true;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
		}
		return false;
	}
	
	private void callRegistry()
	{
		Util.hideSoftKeyboard(mContext, et_email);
		String FirstName, LastName, Password, Email, ComfirmEmail, Birthay;
		try
		{
			FirstName = this.et_firstname.getText().toString().trim();
			LastName = this.et_lastname.getText().toString().trim();
			Password = this.et_password.getText().toString().trim();
			Email = this.et_email.getText().toString().trim();
			ComfirmEmail = this.et_confirmemail.getText().toString().trim();
			
			
			if(!isEmptyAll(FirstName, LastName, Password, Email, ComfirmEmail))
			{
				if(isEqualMail(Email, ComfirmEmail))
				{
					if(isEmailValid(Email, ComfirmEmail))
					{
						if(Util.getNetworkStatus(mContext))
						{
							hashMap = new HashMap<String,String>();
							
							hashMap.put("email", Email);
							hashMap.put("properties[email]", Email);
							hashMap.put("password",Password);
							hashMap.put("first_name", FirstName);
							hashMap.put("properties[first_name]", FirstName);
							hashMap.put("properties[last_name]", LastName);
							hashMap.put("last_name", LastName);
							hashMap.put("properties[gender]", mGender);
							hashMap.put("properties[birthday]", birthday +"");
							Log.e(TAG, "Data Post Register:  " + hashMap.toString());
							
							AsyncTask_Api apiTask = new AsyncTask_Api(this, this, 0, 0, ScreenStopper.STYLE_PROGRESS_PROCESS);
					    	apiTask.execute();
						}
						else
						{
							Util.showDialog(this, R.string.warning, R.string.network_not_available, R.drawable.exclamation);
						}
					}
					else
					{
						Util.showDialog(this, R.string.warning, R.string.msg_error_incorret_gmail, R.drawable.exclamation);
					}
				}
				else
				{
					Util.showDialog(this, R.string.warning, R.string.msg_error_gmail_match, R.drawable.exclamation);
				}
			}
			else
			{
				Util.showDialog(this, R.string.warning, R.string.msg_error_empty_infor, R.drawable.exclamation);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		finally 
		{
			
		}
	}

	@Override
	public void tokenExpride() {
		// TODO Auto-generated method stub
		
	}
	
}
